<?php

	require_once "config.php";
	require_once dirname(__FILE__). '/util/connection.class.php';
	require_once dirname(__FILE__). '/util/TimeUtil.php';
	require_once dirname(__FILE__). '/util/record.php';
	set_time_limit(60*60);
	ini_set('memory_limit', '512M');

	$g_start = microtime(true);

	$tag = 'offersofweek';
	$dbconn = Connection::getInstance();
	
	
	$test = false;
	
	if (isset($argv[1]) && $argv[1] == 'test') {
		$test = true;
	}
	else
	{
		$test = false;
	}
	
	if(isset($argv[2]) && $argv[2] != ''){
		$subjectFrom_argv = $argv[2];
	}
	
	$switch = getOfferEmailSwitch($dbconn);
	if ($switch == 'off' && !$test)
		exit('Not Avalilable, please check config');
	
	$sitesInfo = getSitesInfo($dbconn);
	
	foreach ($sitesInfo as $site) {
		$emailOffers = getEmailOffersBySite($site['id'], $dbconn);
		if (count($emailOffers) === 0) {
			continue;
		} else {
			$template = getTemplate($tag, $site['template']);
			if(!isset($subjectFrom_argv) || $subjectFrom_argv == ''){
				//$subject = getEmailSubject($tag, $site['template'], $dbconn, 'db', $site['id']);
				$subject = $emailOffers[0]['subject'];
			}
//			foreach($emailOffers as $k=>$emailOffer){
//				if($emailOffer['banner_picture_url'] != ''){
//					setSiteEmailOfferBanner($site['id'], $emailOffer['id'], $dbconn);	
//					break;
//				}
//			}
			$usersWithOffers = getUsers($dbconn, $site['id'], $test);
			if(!empty($usersWithOffers)){
				foreach ($usersWithOffers as $user) {
					$args = array();
					$args['firstname'] = $user['firstname'];
					
					$emailSubject = array();
					foreach ($emailOffers as $index => $emailOffer) {
						if(empty($emailOffer['gender']) || (!empty($emailOffer['gender']) && $emailOffer['gender'] == $user['gender'])){
							$emailSubject[] = $emailOffer['subject'];
						}
					}
					if(count($emailSubject) == 0){
						continue;
					}else{
						$subject = $emailSubject[0];
					
						$translatedSubject = translate($subject, $args);
						
						$emailId = addSentEmailToDb($site['name'], 'no-reply@' . strtolower($site['domain']), $translatedSubject, $user['email'], $dbconn);
								
						$record = new Record($user['id']);
						$record->addEmailSentRecording('offersofweek', date('Y-m-d'));
						
						$emailOfferString = '';
						$links = array();
						$indexCount = 0;
						foreach ($emailOffers as $index => $emailOffer) {
							if(empty($emailOffer['gender']) || (!empty($emailOffer['gender']) && $emailOffer['gender'] == $user['gender'])){
								$uid = getFormattedUserId($emailOffer['offer_name'], $user['id'], $site['domain']);
								$emailOffer['link_url'] .= getParamsOfLinkUrl($emailOffer['offer_name']);
								$links[] = str_replace(array('INSERT_END_USER_ID', '[[email_id]]', 'INSERT_END_USER_EMAIL'), array($uid, $emailId, $user['email']), $emailOffer['link_url']);
								$indexCount++;
								$emailOffer['link_url'] = sprintf("http://www." . $site['domain'] . "/default/offerstat/emailId/%d/offer/offer%d_link", $emailId, $indexCount);
								$emailOfferString .= buildEmailOfferHtml($emailOffer);
							}
						}
						$args['emailOffer'] = $emailOfferString;
						$args['emailId'] = $emailId;
						
						$translatedTemplate = translate($template, $args);
						updateEmailId($emailId, $translatedTemplate, $dbconn);
						
						storeOfferLinksInfo($emailId, $links, $dbconn);
					}
				}
				//storeDailyEmailOffersIdArray($emailOffers, $site['id'], $dbconn);
			}
		}
	}
	
	echo ''. microtime(true) - $g_start . "seconds \n";
	echo "memory: " . memory_get_peak_usage() . " bytes \n";

	function getSitesInfo($db) {
		$sql = 'select id, domain, name, template from sites';
		try{
			$sites =  $db->query($sql);
			$temp = array();
			foreach ($sites as $site) {
				$temp[$site['id']] = $site;
			}
			return $temp;
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	function getUsers(Connection $db, $site_id, $test)
	{
//		$sql = "select distinct u.id, u.email, u.firstname from users u left join rewards r on u.id = r.user_id where u.site_id=? and u.unsub=0 and r.id is not null and MOD(u.id, 7)=? order by r.id desc"; 
		try{
			if ($test) {
				$sql = "select id, email, firstname, gender from users where site_id=? and (id = 1 or id = 32 or id = 6) and filtered = 0 LIMIT 50000";
				return $db->query($sql, array($site_id));
			} else {
				$sql = "select id, email, firstname, gender from users where unsub=0 and site_id=? and filtered = 0";
				return $db->query($sql, array($site_id));
			}			
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}


	function getTemplate($tag, $site_template)
	{
		$template_name = TEMPLATE_ROOT .'/'.$site_template . '/email/' . $tag . '.html';
		//$template_name = TEMPLATE_ROOT .'/lalaloot.com/email/' . $tag . '.html';
		if(file_exists($template_name))
		{
			if(is_readable($template_name))
			{
				$template = file_get_contents($template_name);
				return $template;
			}
		}
	}
	
	function addSentEmailToDb($sender, $sendfrom, $subject, $sendto, Connection $db){
		$sql = "insert into emails set sender=?, sendfrom=?, subject=?, sendto=?, created=?, sent=?, priority=10, email_type='offersofweek'";
		try{
			return $db->execute($sql,array($sender, $sendfrom, $subject, $sendto, time(), 0), true);
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	function updateEmailId ($id, $content, $db) {
		$sql = "update emails set content=? where id=?";
		try{
			return $db->execute($sql,array($content, $id));
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	function translate($content, $args){
		foreach ($args as $k => $v){
			$content = str_replace('[[' . $k . ']]', $v, $content);
		}
		return $content;
	}
	
	function getEmailSubject($tag, $site_template, $db, $config_dbOrFile = 'file', $site_id = 1){
		if($config_dbOrFile == 'file'){
			$config = TEMPLATE_ROOT.'/'.$site_template . '/email/email.ini';
			$subjects = parse_ini_file($config);
			$subject = isset($subjects[$tag]) ? $subjects[$tag] :false;
		}else if($config_dbOrFile == 'db'){
			try {
				switch($tag){
					case 'offersofweek':
						$sql = " SELECT v FROM configs WHERE k=? ";
						$result = $db->query($sql, array('offerEmailSubject'.$site_id));
						$subject = $result[0]['v'];
						break;
					default:
						break;
				}
			}catch (Exception $e) {
				Qlog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), Qlog::ERR);
				throw new Model_Exception($e->getMessage, $e->getCode());
			}
			
		}
		return $subject;
	}
	
	function getEmailOffersBySite($site_id, $db) {
		$sql = 'SELECT * FROM email_offers WHERE (site_id=? OR site_id=0) AND tosent_date=? ORDER BY ord';
		try {
			return $db->query($sql, array($site_id, date('Y-m-d')));
		} catch (Exception $e) {
			Qlog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), Qlog::ERR);
			throw new Model_Exception($e->getMessage, $e->getCode());
		}
	}
	
	function getFormattedUserId($offerName, $userId, $siteDomain) {
		$uid = 0;
		switch ($offerName) {
			case 'PeanutLabs':
				if ($siteDomain == 'lalaloot.com') {
					$uid = $userId.'-4684-'.substr(md5($userId.'4684'.'7a023e4a695dd2735bdd3d407b575fea'), 0, 10);
				} elseif ($siteDomain == 'cashdazzle.com') {
					$uid = $userId.'-4676-'.substr(md5($userId.'4676'.'f211973200aed87ef558d3ec364765dc'), 0, 10);
				} else {
					$uid = $userId.'-4712-'.substr(md5($userId.'4712'.'e3d24dc5754aa85b269054f688423a52'), 0, 10);
				}
				break;
			case 'SponsorPay':
			case 'RadiumOne':
			case 'SuperRewards':
				$uid = $userId;
				break;
			default:
				$uid = 0;
		}
		return $uid;
	}
	
	function getParamsOfLinkUrl($offerName) {
		$params = '';
		switch ($offerName) {
			case 'PeanutLabs':
				$params = '&var_key_2=em&var_val_2=[[email_id]]';
				break;
			case 'SuperRewards':
				$params = '&custom_em=[[email_id]]';
				break;
			case 'RadiumOne':
				$params = '&trackId=[[email_id]]';
				break;
			case 'SponsorPay':
				$params = '&pub1=[[email_id]]';
				break;
			default:
				$params = '';
		}
		return $params;
	}
	
	function buildEmailOfferHtml($emailOffer) {	
		$html = '<div style="text-align:center; padding-bottom: 15px;"><a href="';
		$html .= $emailOffer['link_url'] . '" target="_blank"><img src="' . $emailOffer['picture_url'] . '" alt="'. $emailOffer['name']. '" width="' . $emailOffer['picture_width'] . '" height="' . $emailOffer['picture_height'] . '" /></a></div>';
		return $html;
	}
	
	function getOfferEmailSwitch($db){
		$sql = "SELECT v FROM configs WHERE k='offerEmailSwitch'";
		try {
			$result = $db->query($sql);
			return $result[0]['v'];
		} catch (Exception $e) {
			Qlog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), Qlog::ERR);
			throw new Model_Exception($e->getMessage, $e->getCode());
		}
	}
	
	function setSiteEmailOfferBanner($siteId, $emailOfferId, $dbconn)
	{
		try {
			$sql = " SELECT * FROM configs WHERE k=? ";
			$result = $dbconn->query($sql, array('siteId_' . $siteId));
			if(empty($result)){
				$sql = " INSERT INTO configs SET v=?, k=? ";
			}else {
				$sql = " UPDATE configs SET v=? WHERE k=? ";
			}
			return $dbconn->execute($sql, array($emailOfferId, 'siteId_' . $siteId));
		} catch (Exception $e) {
			Qlog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), Qlog::ERR);
			throw new Model_Exception($e->getMessage, $e->getCode());
		}		
	}
	
	function storeOfferLinksInfo($emailId, $links, $dbconn) {
		$args = array_pad($links, 5, '');
		$args[] = $emailId;
		$args[] = date('YmdHis');
		$sql = "insert into email_links set offer1_link=?, offer2_link=?, offer3_link=?, offer4_link=?, offer5_link=?, email_id=?, created=?";
		try{
			return $dbconn->execute($sql,$args);
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	function storeDailyEmailOffersIdArray($emailOffers, $site_id, $db)
	{
		$idArray = array();
		foreach($emailOffers as $emailoffer){
			$idArray[] = $emailoffer[id];
		}
		
		$sql = " INSERT INTO `daily_email_offers` SET offer_ids = ?, site_id = ?, created_date =? ";
		
		return $db->execute($sql, array(serialize($idArray), $site_id, date('Y-m-d')));
	}
	